$(function(){


   
    // 设置变量用来接收被点击时的参数
    let ShopId = 0
    let AreaId = 0
    pageChange(0,0)

     // 定义商城和地址按钮
     let shopBtn = $('nav ul li:eq(0)')
     let areaBtn = $('nav ul li:eq(1)')

     shopBtn.click(function(){
       if($('.show').css('display')=='none'){
        $('.show').css('display','block')  
        getShop()

        $('.show ul li').click(function(){
            ShopId = $(this).attr('shopId')
            console.log(ShopId,AreaId)
            if(AreaId == undefined){
                AreaId = 0
            }
           

           pageChange(ShopId,AreaId)
        })


       }else{
        $('.show').css('display','none')
       }
     })


     areaBtn.click(function(){
        
        if($('.show').css('display')=='none'){
            $('.show').css('display','block')  
            getArea()

            $('.show ul li').click(function(){
                
                AreaId = $(this).attr('areaid')
                console.log(ShopId,AreaId)
                if(ShopId == undefined){
                    ShopId = 0
                }
                pageChange(ShopId,AreaId)
            })

            


           }else{
            $('.show').css('display','none')
           }
     })


















    // 封装获取商城信息函数
    function getShop(){
        $.ajax({
            method:'get',
            async:false,
            url:'http://chst.vip:1234/api/getgsshop',
            success:function(res){
               console.log(res.result);
               let str =  ''
                res.result.forEach(element => {
                    str+=`<li shopId=${element.shopId}>${element.shopName}</li>`
                });
                $('.show ul').html(str)
            }
        })
    }
   


    //  封装获取地址信息函数
    function getArea(){
        $.ajax({
            async:false,
            method:'get',
            url:'http://chst.vip:1234/api/getgsshoparea',
            success:function(val){
                let str1 = ``
                val.result.forEach(item=>{
                    str1+=`<li areaid=${item.areaId}>${item.areaName}</li>`
                })
                $('.show ul').html(str1)
            }
        })
    }

    



   



    // 封装渲染页面函数
    function pageChange(nowSid,nowAid){
        fetch(`http://chst.vip:1234/api/getgsproduct?shopid=${nowSid}&areaid=${nowAid}`).then(response=>{
            return response.json()
        })
        .then(res=>{
            let listr = ``
            res.result.forEach(item=>{
                listr+=` <li>
                            <img src=${item.productImg.match(/[0-9a-zA-Z:/.]+/g)[0]} alt="">
                            <p>${item.productName}</p>
                            <h4>${item.productPrice}</h4>
                        </li>`
            })
            $('main ul').html(listr)
        })
    }

    toTop2()
})